<template>
  <div class="my-pets">
    <div class="container">
      <h1 class="page-title">我的宠物</h1>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="adoptedPets.length === 0" class="empty-container">
        <el-empty description="您还没有成功领养宠物">
          <router-link to="/pets">
            <el-button type="primary">去看看宠物</el-button>
          </router-link>
        </el-empty>
      </div>
      
      <div v-else class="pet-grid">
        <div v-for="pet in adoptedPets" :key="pet.application_id" class="pet-card-wrapper">
          <el-card class="pet-card">
            <div class="pet-card-content">
              <div class="pet-image-container">
                <img :src="getPetImageUrl(pet)" :alt="pet.name" class="pet-image">
              </div>
              <div class="pet-info">
                <h3 class="pet-name">{{ pet.name }}</h3>
                <div class="pet-meta">
                  <div class="meta-item">
                    <span class="meta-label">品种:</span>
                    <span class="meta-value">{{ pet.breed || '未知' }}</span>
                  </div>
                  <div class="meta-item">
                    <span class="meta-label">性别:</span>
                    <span class="meta-value">{{ formatGender(pet.gender) }}</span>
                  </div>
                  <div class="meta-item">
                    <span class="meta-label">年龄:</span>
                    <span class="meta-value">{{ formatAge(pet.age) }}</span>
                  </div>
                </div>
                <div class="adoption-info">
                  <span class="adoption-label">领养日期:</span>
                  <span class="adoption-date">{{ formatDate(pet.adoption_date) }}</span>
                </div>
              </div>
            </div>
            <div class="pet-card-footer-cancel">
              <el-button 
                 type="danger" 
                plain 
                 @click="cancelAdoption(pet)"
                 :loading="cancellingAdoption[pet.application_id]"
              >
                 取消领养
              </el-button>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import axios from 'axios';

export default {
  name: 'MyPets',
  data() {
    return {
      feedbackDialogVisible: false,
      selectedPet: null,
      submittingFeedback: false,
      feedbackForm: {
        content: '',
        photos: []
      },
      adoptedPets: [],
      loading: true,
      cancellingAdoption: {} // 用于管理每个卡片的取消 loading 状态
    };
  },
  computed: {
    ...mapGetters({
      categories: 'categories/allCategories',
      currentUser: 'auth/currentUser'
    })
  },
  async created() {
    // 确保类别数据已加载
    if (this.categories.length === 0) {
      await this.fetchCategories();
    }
    
    // 获取已领养宠物
    await this.fetchMyAdoptedPets();
  },
  methods: {
    ...mapActions({
      fetchCategories: 'categories/fetchCategories'
    }),
    async fetchMyAdoptedPets() {
      try {
        this.loading = true;
        const response = await axios.get('/api/adoptions/my-pets', {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        });
        
        if (response.data) {
          this.adoptedPets = response.data;
        }
      } catch (error) {
        console.error('获取已领养宠物失败:', error);
        this.$notify({
          title: '错误',
          message: '获取已领养宠物信息失败',
          type: 'error'
        });
      } finally {
        this.loading = false;
      }
    },
    formatGender(gender) {
      const genderMap = {
        'male': '公',
        'female': '母',
        'unknown': '未知'
      };
      return genderMap[gender] || '未知';
    },
    formatAge(age) {
      if (!age) return '未知';
      return `${age} 岁`;
    },
    formatDate(dateString) {
      if (!dateString) return '未知';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    },
    getCategoryName(categoryId) {
      if (!categoryId) return '未知';
      const category = this.categories.find(c => c.id === categoryId);
      return category ? category.name : '未知';
    },
    getPetImageUrl(pet) {
      const imageUrl = pet.image_url;
      console.log('尝试加载图片URL:', imageUrl);
      return imageUrl;
    },
    async cancelAdoption(pet) {
      try {
        // 弹出确认框
        await this.$confirm(`确定要取消对 ${pet.name} 的领养吗？
取消后将无法撤销此操作。`, '提示', {
          confirmButtonText: '确定取消',
          cancelButtonText: '我再想想',
          type: 'warning'
        });
        
        // 用户点击确定后
        this.cancellingAdoption[pet.application_id] = true;
        
        // 调用后端 API 取消领养
        await axios.put(`/api/adoptions/cancel/${pet.application_id}`, null, {
           headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        });
        
        // 取消成功，从列表中移除该宠物
        this.adoptedPets = this.adoptedPets.filter(p => p.application_id !== pet.application_id);
        
        this.$message({
          type: 'success',
          message: `${pet.name} 的领养已取消！`
        });
        
      } catch (error) {
        // 用户点击取消或API请求失败
        if (error !== 'cancel') { // 如果不是用户点击取消按钮
           console.error('取消领养失败:', error);
           let errorMessage = '取消领养失败，请稍后重试';
           if(error.response && error.response.data && error.response.data.message) {
             errorMessage = error.response.data.message;
           }
           this.$message({
             type: 'error',
             message: errorMessage
           });
        }
      } finally {
         this.cancellingAdoption[pet.application_id] = false;
      }
    },
    viewPetDetails(petId) {
      // ... existing code ...
    }
  }
}
</script>

<style lang="scss" scoped>
.my-pets {
  padding: 40px 0;
}

.loading-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.pet-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.pet-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.pet-card-content {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}

.pet-image-container {
  margin-bottom: 15px;
}

.pet-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.pet-info {
  flex-grow: 1;
}

.pet-name {
  font-size: 1.5rem;
  margin-bottom: 15px;
  color: var(--secondary-color);
}

.pet-meta {
  margin-bottom: 15px;
}

.meta-item {
  display: flex;
  margin-bottom: 8px;
}

.meta-label {
  font-weight: bold;
  width: 60px;
  color: var(--gray-color);
}

.meta-value {
  flex-grow: 1;
}

.adoption-info {
  display: flex;
  margin-top: auto;
  padding-top: 15px;
  border-top: 1px dashed #eee;
}

.adoption-label {
  font-weight: bold;
  margin-right: 10px;
  color: var(--primary-color);
}

.adoption-date {
  color: var(--text-color);
}
</style> 